package cz.acies.uniql.sql;

import cz.acies.uniql.dialect.Dialect;
import cz.acies.uniql.dialect.MSSQLDialect;

public class DropTable extends Query
{
	private static final long serialVersionUID = -7420924249365374000L;
	
	// ----- Class Variables --------------------------------------------------
	
	private String schema = null;
	private String tableName = null;
	private boolean allowIfExists = false;
	
	// ----- Construtors ------------------------------------------------------
	
	public DropTable() {
	}

	// -----  -----------------------------------------------------------------
	
	public String toSQLString() throws Exception {
		return this.translate();
	}

	public String translate() throws Exception {
		Dialect dialect = this.getDialect();
		String schema = this.getSchema();
		StringBuilder sb = new StringBuilder();
		if (dialect instanceof MSSQLDialect) {
			if (this.isAllowIfExists()) {
				String tblname = ""; 
				if (schema != null && schema.length() > 0) {
					tblname += schema  + ".";
				}
				tblname += dialect.transferAlias(this.getTableName());				
				sb.append("IF OBJECT_ID(N'"+tblname+"', N'U') IS NOT NULL" + "\n");
			}
			sb.append("DROP TABLE ");
			if (schema != null && schema.length() > 0) {
				sb.append(dialect.CTI_LQ() + schema + dialect.CTI_RQ() + ".");
			}
			sb.append(dialect.LQ() + dialect.transferAlias(this.getTableName()) + dialect.RQ());
		} else {
			sb.append("DROP TABLE ");
			if (this.isAllowIfExists()) {
				sb.append("IF EXISTS ");
			}
			if (schema != null && schema.length() > 0) {
				sb.append(dialect.CTI_LQ() + schema + dialect.CTI_RQ() + ".");
			}
			sb.append(dialect.LQ() + dialect.transferAlias(this.getTableName()) + dialect.RQ());
		}
		return sb.toString();
	}

	// -----  -----------------------------------------------------------------
	
	public String getSchema() {
		if (this.schema == null) {
			if (this.getDialect() != null) {
				this.schema = this.getDialect().getSchema();	
			}
		}		
		return schema;
	}

	public DropTable setSchema(String schema) {
		this.schema = schema;
		return this;
	}

	public String getTableName() {
		return tableName;
	}

	public DropTable setTableName(String tableName) {
		if (getDialect().isKeyword(tableName.toUpperCase())) {
			tableName = getDialect().getKeywords().getKeywordAlter(tableName.toUpperCase());
		}
		this.tableName = tableName;
		return this;
	}

	public boolean isAllowIfExists() {
		return allowIfExists;
	}

	public void setAllowIfExists(boolean allowIfExists) {
		this.allowIfExists = allowIfExists;
	}	
}
